<template>
  <el-dialog
    title="创建开发数据导出任务"
    :visible="dialogVisible"
    append-to-body
    width="36rem"
    :close-on-click-modal="false"
    @close="onClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        label="任务名称"
        prop="taskName"
      >
        <el-input
          v-model="form.taskName"
          style="width:26.5rem"
        />
      </el-form-item>

      <el-form-item
        label="导出模式"
        prop="exportModel"
      >
        <el-radio-group
          v-model="form.exportModel"
          @change="exportModelChange"
        >
          <!--          <el-radio label="source">按源导出</el-radio>-->
          <el-radio label="database">按库导出</el-radio>
          <el-radio label="table">按表导出</el-radio>
          <el-radio label="custom">自定义导出</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.exportModel === 'source'"
        label="源名称"
        prop="sourceName"
      >
        <el-select
          v-model="form.sourceName"
          style="width:26.5rem"
        >
          <el-option
            v-for="sourceName in sourceList"
            :key="sourceName"
            :value="sourceName"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.exportModel === 'database' || form.exportModel === 'table'"
        prop="databaseName"
        label="库名称"
      >
        <el-select
          v-model="form.databaseName"
          style="width:26.5rem"
          @change="databaseNameChange"
        >
          <el-option
            v-for="item in databaseList"
            :key="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.exportModel === 'database'"
        label="导出方式"
        prop="exportType"
      >
        <el-radio-group v-model="form.exportType">
          <el-radio label="increment">增量表</el-radio>
          <el-radio label="complete">全量表</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.exportModel === 'table'"
        prop="tableNameList"
        label="表名称"
      >
        <el-select
          v-model="form.tableNameList"
          filterable
          multiple
          collapse-tags
          style="width:26.5rem"
        >
          <el-option
            v-for="item in tableList"
            :key="item.tblName"
            :label="item.tblName"
            :value="item.tblName"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.exportModel === 'custom'"
        label="自定义清单"
        prop="customTableListPath"
      >
        <el-upload
          ref="upload"
          class="upload-demo"
          style="display: inline-block;margin: 0 10px"
          action=""
          accept=".xlsx, .xls"
          :limit="5"
          :auto-upload="false"
          :on-change="handleChange"
          :file-list="fileList"
          :show-file-list="true"
        >
          <el-button
            size="small"
            type="primary"
          >点击上传</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
          >只能上传xlsx/xls，且不超过500kb,
            <el-link
              type="primary"
              @click="downloadTemplate('开发数据同步导出表清单', 'template/dev_data_export_table_list.xlsx')"
            >下载模板</el-link>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item
        v-if="form.exportType !== 'complete' || form.exportModel === 'table' || form.exportModel === 'custom'"
        prop="quickDate"
        label="日期范围"
      >
        <el-select
          v-model="form.quickDate"
          style="width:26.5rem"
        >
          <el-option
            v-for="item in dateList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.quickDate == 'custom'"
        prop="dateList"
        label="自定义日期"
      >
        <el-date-picker
          v-model="form.dateList"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="yyyy-MM-dd"
          style="width:26.5rem"
        />
      </el-form-item>

      <el-form-item
        prop="filePath"
        label="导出路径"
      >
        <el-input
          v-model="form.filePath"
          disabled
          style="width:26.5rem"
        />
      </el-form-item>
    </el-form>

    <span
      slot="footer"
      style=" display: flex; align-items: center; justify-content: center;"
    >
      <el-button
        size="medium"
        type="primary"
        :loading="submitLoading"
        @click="submitCU"
      >保存</el-button>
      <el-button
        size="medium"
        @click="onClose"
      >返回</el-button>
    </span>
  </el-dialog>
</template>

<script>
import sourceRuleTableViewApi from '@/api/dataTransfer/common/sourceRuleTableView'
import devDataExportTask from '@/api/dataTransfer/devDataTransfer/devDataExportTask'
import cdhMetadataApi from '@/api/dataTransfer/common/cdhMetadata'
import desensitizationFieldsTaskApi from '@/api/dashboard/desensitizationFieldsTask'

const defaultForm = {
  exportModel: 'table',
  sourceName: null,
  databaseName: '',
  quickDate: 'lastMonth',
  tableNameList: [],
  dateList: [],
  exportType: 'increment',
  customTableListPath: null,
  filePath: '/data_cdh/backup/dmpro/dev-data'
}
export default {
  props: {
    dialogVisible: Boolean,
    onClose: Function
  },
  data() {
    return {
      form: {},
      submitLoading: false,
      fileList: [],
      rules: {
        taskName: [
          {required: true, message: '请输入导出任务名', trigger: 'blur'}
        ],
        exportModel: [
          {required: true, message: '请选择导出模式', trigger: 'blur'}
        ],
        sourceName: [
          {required: true, message: '请选择导出源', trigger: 'blur'}
        ],
        exportType: [
          {required: true, message: '请选择导出类型', trigger: 'blur'}
        ],
        databaseName: [
          {required: true, message: '请选择导出库名', trigger: 'blur'}
        ],
        tableNameList: [
          {required: true, message: '请选择导出表', trigger: 'blur'}
        ],
        customTableListPath: [
          {required: true, message: '请上传自定义清单', trigger: 'change'}
        ],
        quickDate: [
          {required: true, message: '请选择导出日期范围', trigger: 'blur'}
        ],
        dateList: [
          {required: true, message: '请选择导出日期范围', trigger: 'blur'}
        ],
        filePath: [
          {required: true, message: '请输入导出文件存储路径', trigger: 'blur'}
        ]
      },
      databaseList: [],
      tableList: [],
      sourceList: [],
      dateList: [
        {label: '最近7天数据', value: 'lastWeek'},
        {label: '最近30天数据', value: 'lastMonth'},
        {label: '最近半年数据', value: 'lastSixMonths'},
        {label: '最近一年数据', value: 'lastYear'},
        {label: '最近两年数据', value: 'lastTwoYears'},
        {label: '自定义', value: 'custom'}
      ]
    }
  },
  created() {
    this.form = JSON.parse(JSON.stringify(defaultForm))
    this.exportModelChange('table')
  },
  methods: {
    checkFileSuffix(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)

      console.log(fileSuffix)
      const whiteList = ['xlsx', 'xls']

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error('上传文件只能是 xlsx、xls格式')
        return false
      } else {
        return true
      }
    },
    downloadTemplate(fileName, fileUrl) {
      const a = document.createElement('a')
      const evt = document.createEvent('MouseEvents')
      a.download = `${fileName}.xlsx`
      a.href = fileUrl
      evt.initEvent('click', true, true)
      a.dispatchEvent(evt)
      window.URL.revokeObjectURL(a.href)
    },
    handleChange(file, fileList) {
      this.fileList = []
      if (!this.checkFileSuffix(file)) {
        return
      }
      this.fileList.push(file)
      const formData = new FormData()
      formData.append('file', file.raw)
      devDataExportTask.upload(formData).then(res => {
        if (res != null) {
          this.form.customTableListPath = res
          this.$notify({title: '成功', message: '上传成功！', type: 'success'})
        } else {
          this.$notify({title: '警告', message: '请选择要上传的文件！', type: 'warning'})
        }
      })
    },
    exportModelChange(exportModel) {
      this.databaseList = []
      this.sourceList = []
      this.form.sourceName = null
      this.form.databaseName = null
      this.form.tableNameList = []
      if (exportModel === 'database' || exportModel === 'table') {
        cdhMetadataApi.databases().then(res => {
          this.databaseList = res
        })
      } else {
        sourceRuleTableViewApi.sources().then(res => {
          this.sourceList = res
        })
      }
    },
    databaseNameChange(databaseName) {
      this.tableList = []
      this.form.tableNameList = []
      cdhMetadataApi.tables(databaseName).then(res => {
        this.tableList = res
      })
    },
    submitCU() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        this.addTask()
      })
    },
    async addTask() {
      await desensitizationFieldsTaskApi.reset()
      await devDataExportTask.createTask(this.form).then(() => {
        this.submitLoading = false
        this.$notify({title: '成功', message: '创建成功！', type: 'success'})
        this.onClose()
      }).then(() => {
        this.submitLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
